package org.example.study4;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 使用原子类（AtomicInteger）实现无锁线程安全
 */
public class Demo_413 {
    public static void main(String[] args) throws InterruptedException {
        Counter413 counter = new Counter413();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("count = " + counter.getCount());
    }
}

class Counter413 {
    private final AtomicInteger count = new AtomicInteger(0);

    public void increase() {
        count.incrementAndGet(); // CAS原子操作
    }

    public int getCount() {
        return count.get();
    }
}
// 运行结果：count = 100000
